<template>
<t-space :size="32" direction="vertical" style="width: 100%">
    <t-space direction="vertical" style="width: 80%">
     <t-space>
       <t-form layout="inline">
         <t-form-item label="导航名称">
           <t-input v-model="formData.label" placeholder="请输入导航名称" class="nav-input">
             <template #prefix-icon>
                     <caret-right-icon />

                   </template>
           </t-input>
           </t-form-item>
         <t-form-item label="导航链接">
           <t-input v-model="formData.value" placeholder="请输入导航链接" class="nav-input">
             <template #prefix-icon>
                     <link-icon />
                   </template>
           </t-input>
           </t-form-item>
         <t-form-item>
           <t-button @click="append()">添加一级导航</t-button>
         </t-form-item>
       </t-form>

     </t-space>
    </t-space>
    <t-tree
      ref="tree"
      :data="items"
      hover
      draggable
      activable
      :checkable="false"
      expand-all
      :height="300"
      :transition="transition"
      :expand-on-click-node="false"
      :line="showLine"
      :icon="showIcon"
      :label="label"
      :scroll="{
        rowHeight: 34,
        bufferSize: 10,
        threshold: 10,
        type: 'virtual',
      }"

  @drag-end="handleDragEnd2"
      @click="handleClick"
    >
      <template #operations="{ node }">
        <div v-if="isOperateAble" class="tdesign-demo-block-row">
          <t-button size="small" variant="outline" @click="append(node)">添加下级导航</t-button>
          <t-button size="small" variant="outline" theme="danger" @click="remove(node)">删除</t-button>
        </div>
      </template>
    </t-tree>
    <div style="height: 100px"></div>
  </t-space>

</template>

<script lang="ts" setup>
import { ref, computed, onMounted ,watch} from 'vue';
import {MessagePlugin, TreeProps, TreeInstanceFunctions, TreeOptionData, TypeTreeNodeModel } from 'tdesign-vue-next';
import {LinkIcon,CaretRightIcon } from 'tdesign-icons-vue-next'
  import {  saveSettings } from '@/api/settings'
import {
    settingModel
  } from '@/api/model/settingsModel';

const props=defineProps({
    data:{
      type:Array<settingModel>
    }
  });
const virtualTree = createTreeData();
const tree = ref<TreeInstanceFunctions>();
//动画
const transition = ref(true);
//一次插入节点数量
const textInsertCount = ref('1');
const showLine = ref<TreeProps['line']>(true);
const showIcon = ref<TreeProps['icon']>(true);
//显示操作
const isOperateAble = ref(true);
const items = ref([])

const formData=ref({
  label:'',
  value:''
})
const navigateSetting=ref<settingModel>()

const save=()=>{

    let data=[]
    data.push(navigateSetting.value)
    console.log("saveSettings",JSON.stringify(data))
    saveSettings(data)
      .then(ret => {
        initData(ret)
      })
      .catch(e => {
        if (e.message) {
          MessagePlugin.error(e.message);
        } else {
          MessagePlugin.error(e.msg);
        }
      })

}


const handleDragEnd2=(ctx:any)=>{
  console.log('handleDragEnd', ctx);
    let data=JSON.stringify(tree.value.getTreeData())
    navigateSetting.value.value =data
    save()
}


const handleDragStart=(ctx:any)=>{
  console.log('handleDragStart', ctx);
  console.log('start items',JSON.stringify(items.value));
}

const handleClick=(ctx:any)=>{
  formData.value.label=ctx.node.label
  formData.value.value=ctx.node.value
}

function createTreeData() {

  let cacheIndex = 0;
  function getValue() {
    cacheIndex += 1;
    return `t${cacheIndex}`;
  }

  const items = ref([]);

  return {
    getValue,
    items,
  };
}

const insertCount = computed(() => {
  return parseInt(textInsertCount.value, 2) || 1;
});
const label: TreeProps['label'] = (h, node) => {
  return `${node.label}`;
};

const append = (node?: TypeTreeNodeModel) => {
  if(formData.value.label=='')
  {
    MessagePlugin.error('请输入导航名称');
    return;
  }
  if(formData.value.value=='')
  {
    MessagePlugin.error('请输入导航链接');
    return;
  }

   let item={...formData.value}

  if (!node) {
    for (let index = 0; index < insertCount.value; index += 1) {
      tree.value.appendTo('', item);
    }
  } else {
    for (let index = 0; index < insertCount.value; index += 1) {
      console.log('node.value',node.value)
      tree.value.appendTo(node.value, item);
    }
  }

  let d=tree.value.getItems();
   let target:any=[]
   for(let i=0;i<d.length;i++)
   {
     target.push(d[i].data)
   }



  setTimeout(()=>{
    target.push({label:formData.value.label,value:formData.value.value})
    console.log('target',JSON.stringify(target))
    navigateSetting.value.value=JSON.stringify(target)
     save()
  },1000)

};

const remove = (node: TypeTreeNodeModel) => {
  node.remove(); let d=tree.value.getItems();
  let target:any=[]
   d.map(x=>{
     if(x.label!=node.label&&x.value!=node.value)
     target.push(x.data)
   })
   navigateSetting.value.value=JSON.stringify(target)
   save()
};
const initData=(data:any)=>{
  let d=data.filter(function(item:any){
    if( item.key==='navigation')
    return item
  })
  //console.log('initData d ',JSON.stringify(d))
  navigateSetting.value=d[0]
}


watch(()=>props.data,
()=>{
  initData(props.data)
  //console.log('initDataed',JSON.stringify(navigateSetting.value))
  items.value=JSON.parse(navigateSetting.value.value)
})
</script>

<style scoped>
  .nav-input{
    width: 400px;
  }
</style>
